﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GKBErps.BLL.sys;
using GKBErps.Common;
using GKBErps.Common.ConfigHelper;
using GKBErps.Common.web;
using GKBErps.Model;
using GKBErps.Web.Filters;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MySqlX.XDevAPI;
using Newtonsoft.Json;

namespace GKBErps.Web.Controllers
{
    public class Login : Controller
    {
        private sys_userBLL userBLL = new sys_userBLL();
        private sys_logBll logBll = new sys_logBll();
        protected readonly IHttpContextAccessor httpContextAccessor;
        public Login(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        [NoSign, ErrorHandleAttribute]
        public IActionResult Index()
        {
            return View("login");
        }
        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="loginName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        [NoSign, ErrorHandleAttribute]
        public ActionResult LoginIn(string loginName, string pwd)
        {
            var md5pwd = Md5Crypt.Encrypt(pwd);
            sys_user userModel = userBLL.checkLogin(loginName, md5pwd);
            object jsonResult = CheckUserInfo(userModel);
            var jsonstr = JsonConvert.SerializeObject(jsonResult);
            return Content(jsonstr);
        }
        /// <summary>
        /// 判断用户信息
        /// </summary>
        /// <param name="userModel">当前用户</param>
        /// <returns></returns>
        public object CheckUserInfo(sys_user userModel) {
            if (userModel == null)
            {
                return new{ code = ErrorCode.A0110.ToString(), data = "用户名或密码输入错误，请重新输入!" };
            }
            else
            {
                if (userModel.userStatus == 0)
                {
                    return new { code = ErrorCode.A0203.ToString(), data = "该用户已作废，如有疑问请联系管理员!" };
                }
                HttpContext.Session.SetInt32(SessionKey.USERID.ToString(), userModel.id);
                HttpContext.Session.SetString(SessionKey.USERNAME.ToString(), userModel.userName);
                logBll.InsertLog("ERP", "login", "用户登录", userModel.id, userModel.userName, this.httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(), Request.Headers["User-Agent"].ToString(), "login", "");
                return new { code = ErrorCode.A0000.ToString(), data = userModel };
            }
        }

        #region WriteLoginCookie

      



        #endregion
    }
}
